﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace LWrap.IndexSource
{
    public class DBDataSource:IndexDataSource
    {
        private DataTable _dataToIndex;
        private int _curRowIndex=0;

        public DataTable DataToIndex
        {
            get { return _dataToIndex; }
            set { _dataToIndex = value; }
        }



        public DBDataSource(DataTable dataToIndex)
        {
            this._dataToIndex = dataToIndex;
        }

        public DBDataSource() { }

        private  string DateToString(DateTime dt)
        {
            // If the time is not set (i.e. the time is midnight), 
            // then return the short date (MM/dd/yyyy).
            if ((dt.Hour == 0) && (dt.Minute == 0) && (dt.Second == 0))
            {
                return dt.ToShortDateString();
            }

            // Otherwise, return the default general date (short date 
            // followed by long time, in the appropriate culture).
            else
            {
                return dt.ToString();
            }
        }

        public override bool GetNextDoc()
        {
            if (_curRowIndex >= _dataToIndex.Rows.Count)
            {
                _curRowIndex = 0;
                return false;
            }
            DataRow curRow = _dataToIndex.Rows[_curRowIndex];

            this.DocBytes = null;
            this.DocFields = string.Empty;
            for (int i = 0; i < _dataToIndex.Columns.Count; i++)
            {
                string colName = _dataToIndex.Columns[i].ColumnName;
                string colValue;

                // Process date/time strings using a custom formatter
                if (curRow[i] is DateTime)
                {
                    colValue = DateToString((DateTime)curRow[i]);
                }
                else
                {
                    colValue = curRow[i].ToString();
                }

                // Set the DocFields property; need to convert value 
                // string to one without tabs.
                colValue = colValue.Replace("\t", " ");
                DocFields += colName + "\t" + colValue + "\t";
            }
            _curRowIndex++;

            return true;
        }
    }
}
